import React, { useState } from 'react'
import "./style.less"
import { useHistory } from "react-router-dom"
import api from "../../api"
import { useDispatch } from "react-redux"
import { setUser } from "../../redux/actions/auth"

export default function Login () {

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [msg, setMsg] = useState("")
  const dispatch = useDispatch();


  function changeHandle1 (e) {
    setUsername(e.target.value)
  }
  function changeHandle2 (e) {
    setPassword(e.target.value)
  }

  function onSubmitHandle (e) {
    e.preventDefault();
    console.log({ username, password });
    dispatch(setUser({ username }));
    // 本地存储一下：
    localStorage.setItem("username", username);
    window.history.back();
    // api.login({ username, password }).then(res => {
    //   console.log(res.data);
    //   if (res.data.status === 200) {
    //     setMsg("登录成功");
    //     dispatch(setUser({ username }));
    //     window.history.back();
    //   } else {
    //     setMsg("用户名或密码错误");
    //   }
    // }).catch(error => {
    //   console.log(error);
    // })
  }

  return (
    <div id="login-container">
      <form onSubmit={onSubmitHandle}>
        <div className="input-container phone-container">
          <i className="icon-tablet"></i>
          <input
            type="text"
            onChange={changeHandle1}
            name="username"
            value={username}
          />
        </div>
        <div className="input-container password-container">
          <i className="icon-key"></i>
          {/* <button>发送验证码</button> */}
          <input type="password"
            onChange={changeHandle2}
            name="password"
            value={password}
          />
        </div>
        <p style={{ color: "red" }}>{msg}</p>
        <button className="btn-login">登录</button>
      </form>
    </div>
  )
}
